<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cart extends MIS_Controller 
{
	private $cartArray = array();
	function __construct()
	{
		parent::__construct();
		$this->load->model('m_books');
		$this->cartArray = ($this->session->userdata('cartdata'))?$this->session->userdata('cartdata'): array();
	}

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/buy_books
	 *	- or -  
	 * 		http://example.com/buy-books
	 *	- or -  
	 * 		http://example.com/buy_books/index
	 *	- or -  
	 * 		http://example.com/buy-books/index
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index()
	{
		$this->loadViewData['banner_inc'] = false;
		$this->loadViewData['search_inc'] = false;
		$this->loadViewData['upper_footer_inc'] = false;
		$this->loadViewData['viewFile'] = 'v_cart';
		$this->load->view('layout', $this->loadViewData);
	}
	
	public function add()
	{
		$id = $this->uri->segment(3);
		$id = filter_var($id, FILTER_VALIDATE_INT);
		if($this->input->is_ajax_request())
		{
			$msg = array('stat' => 'NO');
			if($id)
			{
				if($this->m_books->is_book_available_for_sale($id))
				{
					if(isset($this->cartArray[$id])) $msg['mesg'] = "This book is already in your cart.";
					else 
					{
						$book_info = $this->m_books->get_book_details($id);
						$this->cartArray[$id] = array('book_name' => $book_info->Name, 'price' => $book_info->Sell_price, 'quantity' => 1);
						$this->setCartSession();
						$msg['stat'] = 'OK';
					}
				}
				else 
				{
					if(isset($this->cartArray[$id]))
					{
						unset($this->cartArray[$id]);
						$this->setCartSession();
					}
					$msg['mesg'] = "This book is out of stock.";
				}
			}
			else $msg['mesg'] = "No book id provided.";
			$msg['total_item'] = count($this->cartArray);
			$msg['total_item'] .= ($msg['total_item'] > 1) ? " items" : " item";
			print_json($msg);
		}
		else 
		{
			if($id)
			{
				if($this->m_books->is_book_available_for_sale($id))
				{
					if(isset($this->cartArray[$id])) $this->session->set_flashdata('error_mesg',"This book is already in your cart.");
					else 
					{
						$book_info = $this->m_books->get_book_details($id);
						$this->cartArray[$id] = array('book_name' => $book_info->Name, 'price' => $book_info->Sell_price, 'quantity' => 1);
						$this->setCartSession();
						$this->session->set_flashdata('success_mesg',"Book added to cart.");
					}
				}
				else 
				{
					if(isset($this->cartArray[$id]))
					{
						unset($this->cartArray[$id]);
						$this->setCartSession();
					}
					$this->session->set_flashdata('error_mesg',"This book is out of stock.");
				}
			}
			header("location: " . $_SERVER['HTTP_REFERER']);
		}
	}
	
	public function delete()
	{
		$id = $this->uri->segment(3);
		$id = filter_var($id, FILTER_VALIDATE_INT);
		if($this->input->is_ajax_request())
		{
			$msg = array('stat' => 'NO');
			if($id)
			{
				if(isset($this->cartArray[$id]))
				{
					unset($this->cartArray[$id]);
					$this->setCartSession();
					$msg['deleted_book_id'] = $id;
					$msg['stat'] = 'OK';
				}
				else $msg['mesg'] = "Book is not in your cart.";
			}
			else $msg['mesg'] = "Book id not provided.";
			$msg['total_item'] = count($this->cartArray);
			$msg['total_item'] .= ($msg['total_item'] > 1) ? " items" : " item";
			$msg['total_price'] = 0;
			if(count($this->cartArray))
			{
				foreach ($this->cartArray as $item) $msg['total_price'] += ($item['price'] * $item['quantity']);
			}
			$msg['total_price'] = number_format($msg['total_price'], 2, '.', ',');
			print_json($msg);
		}
		else 
		{
			if($id)
			{
				if(isset($this->cartArray[$id]))
				{
					unset($this->cartArray[$id]);
					$this->setCartSession();
					$this->session->set_flashdata('success_mesg',"Book deleted from cart.");
				}
				else $this->session->set_flashdata('error_mesg',"Book is not in your cart.");
			}
			else $this->session->set_flashdata('error_mesg',"Book id not provided.");
			redirect('cart');
		}
	}
	
	public function edit()
	{
		
	}
	
	public function checkout()
	{
		$id = $this->uri->segment(3);
		$id = filter_var($id, FILTER_VALIDATE_INT); 
		if($id)
		{
			if($this->m_books->is_book_available_for_sale($id))
			{
				if(!isset($this->cartArray[$id])) 
				{
					$book_info = $this->m_books->get_book_details($id);
					$this->cartArray[$id] = array('book_name' => $book_info->Name, 'price' => $book_info->Sell_price, 'quantity' => 1);
					$this->setCartSession();
				}
			}
			else 
			{
				if(isset($this->cartArray[$id]))
				{
					unset($this->cartArray[$id]);
					$this->setCartSession();
				}
				$this->session->set_flashdata('error_mesg',"This book is out of stock.");
				redirect('cart');
			}
		}
		
		
		if(count($this->cartArray) > 0)
		{
			if($this->is_loggedin)
			{
				$this->loadViewData['cart_total'] = 0;
				foreach ($this->cartArray as $item) 
				{
					$this->loadViewData['cart_total'] += $item['quantity'] * $item['price'];
				}
				$this->loadViewData['paypal_email'] = $this->config->item('paypal_email');
				$this->loadViewData['paypal_url'] = $this->getPaypalURL();
				
				$this->loadViewData['banner_inc'] = false;
				$this->loadViewData['search_inc'] = false;
				$this->loadViewData['upper_footer_inc'] = false;
				$this->loadViewData['viewFile'] = 'v_checkout';
				$this->load->view('layout', $this->loadViewData);
			}
			else 
			{
				$this->session->set_flashdata('error_mesg',"You need to login before checkout.");
				$this->redirectAfterLogin('cart/checkout');
				redirect('login');
			}
		}
		else 
		{
			$this->session->set_flashdata('error_mesg',"Your cart is empty.");
			redirect('buy-books');
		}
	}
	
	public function paypal_return()
	{
		if(count($this->cartArray))
		{
			if($this->input->get('tx'))
			{
				$pdt = $this->varifyTransaction($this->input->get('tx'));
				$arr = $this->paypalPdtToArray($pdt);
				$total = 0;
				foreach ($this->cartArray as $item) 
				{
					$total = $item['quantity'] * $item['price'];
				}
				if($total == $arr['payment_gross'])
				{
					$this->successPaypal($pdt);
					$this->session->set_flashdata('success_mesg',"Thank you for buying books.");
					redirect('welcome');
				}
				else 
				{
					$this->session->set_flashdata('error_mesg',"Sorry, Your transaction declined.");
					redirect('welcome');
				}
			}
			else show_404();
		}
		else show_404();
		$this->destroyCart();
	}
	
	public function paypal_cancel_return()
	{
		$this->session->set_flashdata('error_mesg',"Your payment was not successful.");
		redirect('buy-books');
		$this->destroyCart();
	}
	
	private function successPaypal($pdt = '')
	{
		$this->load->model('m_order');
		foreach ($this->cartArray as $id => $items)
		{
			$this->m_order->insertOrder($this->session->userdata('id_user'), $this->session->userdata('cart_order_id'), $id, $items['price'], $items['quantity'], $pdt);
		}
	}
	
	private function destroyCart()
	{
		$this->cartArray = null;
		$this->session->unset_userdata('cartdata');
		$this->session->unset_userdata('cart_order_id');
	}
	
	private function setCartSession()
	{
		$this->session->unset_userdata('cartdata');
		if($this->session->userdata('cart_order_id') === FALSE) $this->session->set_userdata('cart_order_id', $this->getRandomNumber());
		$this->session->set_userdata('cartdata', $this->cartArray);
	}
	
	private function getPaypalURL()
	{
		return 
		($this->config->item('paypal_sandbox') == 1)
			? 'https://www.sandbox.paypal.com/cgi-bin/webscr'
			: 'https://www.paypal.com/cgi-bin/webscr';
	}
	
	private function varifyTransaction($txnId)
	{
		if($txnId)
		{
			$postArr = array();
			$postArr['cmd'] = '_notify-synch';
			$postArr['tx'] = $txnId;
			$postArr['at'] = $this->config->item('paypal_auth');
			$postArr['submit'] = 'PDT';
			$this->load->library('curl');
			$paypal_return = $this->curl->simple_post($this->getPaypalURL(), $postArr, array(CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_SSL_VERIFYPEER => FALSE));
			if($paypal_return)
			{
				$this->load->helper('file');
				write_file('temp/order_' . $this->session->userdata('cart_order_id') .".log", $paypal_return);
				return $paypal_return;
			}
		}
		
		return FALSE;
	}
	
	private function paypalPdtToArray($pdt)
	{
		$return = array();
		$tmp = explode("\n", $pdt);
		foreach ($tmp as $line)
		{
			if($line == 'Error: 4020') die('Paypay marchant authentication failure. Please report to site admin.');
			$tmp2 = explode('=', $line, 2);
			if(count($tmp2) == 2)
			{
				$return[$tmp2[0]] = ($tmp2[1]) ? $tmp2[1] : $tmp2[1];
			}
		}
		return $return;
	}
}

/* End of file cart.php */
/* Location: ./application/controllers/cart.php */